<template>
  <div class="user-info">
    <uploader
      :after-read="afterRead"
      v-model="fileList"
      :max-count="1"
      preview-size="150"
      upload-text="请选择您的头像"
    />
    <!-- <input type="file" style="display: none" ref="imgCtrl" @change="selEnd" /> -->
    <!-- <img :src="dalImg(user.avatar)" alt="图片丢了" @click="selImg" /> -->
    <label for=""
      >昵称: <input type="text" placeholder="请输入昵称" v-model="nickName"
    /></label>
    <Button round type="primary" style="width: 80vw" @click="save">保存</Button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { Button, Toast, Uploader } from "vant";
import { useRouter } from "vue-router";
import { userInfoAPI, changeUserInfoAPI } from "../server/auth";
import { dalImg } from "../utils/tools";
import { serveURL } from "../utils/request";
import { post } from "../utils/request";

const { push } = useRouter();
const imgCtrl = ref();
const user = ref("");
const nickName = ref("");
const fileList = ref([]);
// 获取用户信息
userInfoAPI().then((res) => {
  // console.log(res.data, "用户信息");
  user.value = res.data;
  nickName.value = res.data.nickName;
  if (res.data.avatar) {
    fileList.value = [{ url: serveURL + res.data.avatar }];
  } else {
    fileList.value = [
      {
        url: "https://img2.baidu.com/it/u=2142150771,4031198976&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500",
        isImage: true,
      },
    ];
  }
});
// 上传文件
/*----------------------------------------------------------------*/
const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  // console.log(file);
  const formData = new FormData();
  formData.append("file", file.file);
  post("/api/v1/common/upload_file", formData).then((res) => {
    // console.log(res, "文件");
    user.value.avatar = res.data;
  });
};
/*----------------------------------------------------------------*/
// const selEnd = () => {
//   const formData = new FormData();
//   formData.append("file", imgCtrl.value.files[0]);
//   post("/api/v1/common/upload_file", formData).then((res) => {
//     // console.log(res, "文件");
//     user.value.avatar = res.data;
//   });
// };
// // 选择图片
// const selImg = () => {
//   imgCtrl.value.click();
// };
// 点击保存
const save = async () => {
  if (nickName.value) {
    await changeUserInfoAPI({
      nickName: nickName.value,
      avatar: user.value.avatar,
    });
    Toast.success("保存成功");
    setTimeout(() => {
      push({
        name: "user",
      });
    }, 1000);
  } else {
    Toast.fail("请输入昵称");
  }
};
</script>
